package com.yangye.pisecurity.endpoint;

import com.yangye.picommon.enums.PiResultEnum;
import com.yangye.picommon.model.PiResult;
import com.yangye.picommon.utils.RespUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理器
 * @author yangye
 * @date 2019/8/20
 */
@Component
@Slf4j
public class RestAuthenticationEndpoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
		log.error(e.getMessage(), e);
		Throwable cause = e.getCause() == null ? e : e.getCause();
		if (cause instanceof BadCredentialsException) {
			// 用户名或密码错误
			RespUtil.writeJson(response, PiResult.fail(PiResultEnum.BAD_USERNAME_PASSWORD));
			return;
		} else if (cause instanceof DisabledException) {
			// 帐号被禁用
			RespUtil.writeJson(response, PiResult.fail(PiResultEnum.DISABLED));
			return;
		} else {
			// 登录失败
			RespUtil.writeJson(response, PiResult.fail(PiResultEnum.LOGIN_FAILURE));
			return;
		}
	}
}
